(function() {
    'use strict';

    angular
        .module('gatewayApp')
        .controller('MpDialogController', MpDialogController);

    MpDialogController.$inject = ['$timeout', '$scope', '$stateParams', '$uibModalInstance', '$q', 'entity', 'Mp', 'Menu'];

    function MpDialogController ($timeout, $scope, $stateParams, $uibModalInstance, $q, entity, Mp, Menu) {
        var vm = this;

        vm.mp = entity;
        vm.clear = clear;
        vm.save = save;
        vm.menus = Menu.query({filter: 'mp-is-null'});
        $q.all([vm.mp.$promise, vm.menus.$promise]).then(function() {
            if (!vm.mp.menuId) {
                return $q.reject();
            }
            return Menu.get({id : vm.mp.menuId}).$promise;
        }).then(function(menu) {
            vm.menus.push(menu);
        });

        $timeout(function (){
            angular.element('.form-group:eq(1)>input').focus();
        });

        function clear () {
            $uibModalInstance.dismiss('cancel');
        }

        function save () {
            vm.isSaving = true;
            if (vm.mp.id !== null) {
                Mp.update(vm.mp, onSaveSuccess, onSaveError);
            } else {
                Mp.save(vm.mp, onSaveSuccess, onSaveError);
            }
        }

        function onSaveSuccess (result) {
            $scope.$emit('gatewayApp:mpUpdate', result);
            $uibModalInstance.close(result);
            vm.isSaving = false;
        }

        function onSaveError () {
            vm.isSaving = false;
        }


    }
})();
